<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="宿舍楼" prop="buildingId">
        <el-cascader :options="buildingList" v-model="queryParams.buildingIds" clearable
          :props="{ value: 'id', label: 'name', children: 'parkList' }" @change="changeBuilding">
        </el-cascader>
      </el-form-item>
      <el-form-item label="所属楼层" prop="floorId">
        <el-select clearable v-model.number="queryParams.floorId" placeholder="请选择">
          <el-option v-for="item in floorList" :key="item.id" :label="item.floor" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleSomeAdd">批量添加宿舍</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button> -->
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-refresh" size="mini" @click="syncOccupancy">同步宿舍入住人数</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-upload" size="mini" @click="importVClick">导入宿舍信息</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table v-loading="loading" :data="dormitoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属园区" align="center" prop="parkName" />
      <el-table-column label="所属宿舍楼" align="center" prop="buildingName" />
      <el-table-column label="宿舍号" align="center" prop="roomNo" />
      <el-table-column label="宿舍性别" align="center" prop="gender" />
      <el-table-column label="是否是新生宿舍" align="center">
        <template slot-scope="scope">
          {{ scope.row.isNew == "1" ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="所属校区" align="center" prop="campusName" />
      <el-table-column label="住宿费" align="center" prop="chargeStandard" />
      <el-table-column label="床位数量" align="center" prop="bedNum" />
      <el-table-column label="入住人数" align="center" prop="occupancy" />
      <el-table-column label="宿舍图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.images" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="toDormitory(scope.row.id)">查看学生</el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="setMoney(scope.row.id)">设置金额</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改宿舍信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="宿舍楼" prop="buildingId">
          <el-cascader style="width: 100%;" :options="buildingList" v-model="form.buildingIds"
            :props="{ value: 'id', label: 'name', children: 'parkList' }" @change="changeFormBuilding">
          </el-cascader>
        </el-form-item>
        <el-form-item label="选择楼层" prop="floorId">
          <el-select clearable :disabled="isSelectedBuilding" v-model.number="form.floorId" placeholder="选择当前宿舍楼所属的楼层"
            style="width: 100%;">
            <el-option v-for="item in floorList" :key="item.id" :label="item.floor + '楼'" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="起始宿舍号" prop="startNo" v-if="!isSomeAdd">
          <el-input v-model.number="form.startNo" placeholder="请输入起始宿舍号" />
        </el-form-item>
        <el-form-item label="创建数量" prop="num" v-if="!isSomeAdd">
          <el-input v-model.number="form.num" placeholder="请输入创建数量" />
        </el-form-item>
        <el-form-item label="房间号" prop="roomNo" v-if="isSomeAdd">
          <el-input v-model.number="form.roomNo" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="床位数" prop="bedNum">
          <el-input v-model.number="form.bedNum" placeholder="请输入床位数" />
        </el-form-item>
        <el-form-item label="床位费" prop="bedChange" v-if="!isSomeAdd">
          <el-input v-model.number="form.bedChange" placeholder="请输入床位费(/元)" />
        </el-form-item>
        <el-form-item label="入住人数" prop="occupancy" v-if="isSomeAdd">
          <el-input v-model.number="form.occupancy" placeholder="请输入入住人数" />
        </el-form-item>
        <el-form-item label="住宿性别" prop="gender">
          <el-radio v-model="form.gender" label="男">男</el-radio>
          <el-radio v-model="form.gender" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="备注" prop="remark" v-show="isSomeAdd">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="宿舍图片" prop="photoList">
          <image-upload v-model="form.photoList" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 床位 -->
    <el-dialog title="宿舍床位" :visible.sync="showBed">
      <el-table :data="bedList" style="width: 100%;" size="medium ">
        <el-table-column prop="XSXM" label="学生姓名">
          <template slot-scope="scope">
            {{ scope.row.stuName | filterName }}
          </template>
        </el-table-column>
        <el-table-column prop="XH" label="学号">
          <template slot-scope="scope">
            {{ scope.row.stuNo | filterStuCode }}
          </template>
        </el-table-column>
        <el-table-column prop="hasStudent" label="是否为宿舍长">
          <template slot-scope="scope">
            {{ scope.row.isDormitoryHead | filterIsLive }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>


    <el-dialog title="导入" :visible.sync="importV" :before-close="handleClose" center style="text-align: center;">
      <el-row type="flex" class="row-bg" justify="space-around">
        <el-upload center class="upload-demo" drag :auto-upload="false" :limit="1" :on-exceed="handleExceed" action=""
          :file-list="fileList" :on-change="fileChoose">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击选择</em></div>
          <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件 <el-link @click="downloadMode" type="primary"
              size="mini">下载模板</el-link></div>
        </el-upload>
      </el-row>
      <el-table border
        :data="tableData.slice((importcurrentPage - 1) * importpagesize, importcurrentPage * importpagesize)"
        :stripe="true" :current-page.sync="importcurrentPage" max-height="550" style="width: 100%">
        <el-table-column prop="园区" label="园区" width="180">
        </el-table-column>
        <el-table-column prop="楼栋" label="楼栋" />
        <el-table-column prop="宿舍号" label="宿舍号" />
        <el-table-column prop="宿舍性别" label="宿舍性别" />
        <el-table-column prop="床位数" label="床位数" />
        <el-table-column prop="10个月收费标准" label="10个月收费标准" />
      </el-table>
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 15, 20]"
          :page-size="importpagesize" layout="total, sizes, prev, pager, next, jumper" :total="importtotal">
        </el-pagination>
      </div>


      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doImport()">导 入</el-button>
      </span>

    </el-dialog>



  </div>
</template>

<script>
import {
  listDormitory,
  getDormitory,
  delDormitory,
  addDormitory,
  updateDormitory,
  listStudent,
  updateDorm,
  syncOccupancy,
  importDorm
} from "@/api/dormitory/basedata/dormitory";
import {
  listBuilding
} from "@/api/dormitory/basedata/building";
import {
  listFloor, listAllFloor
} from "@/api/dormitory/basedata/floor";

import {
  addSomeDormitory
} from "@/api/dormitory/basedata/dormitory";
import {
  listCampus
} from "@/api/dormitory/campus";
import { fullLoading, isEmpty } from "@/api/helpFunc";

import * as XLSX from 'xlsx';
import { workbook2blob, openDownloadDialog, file2Xce } from "@/api/helpFunc";



export default {
  name: "Dormitory",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 宿舍信息表格数据
      dormitoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        unitId: null,
        floorId: null,
        // 宿舍楼id
        buildingId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        buildingId: [{
          required: true,
          message: "宿舍楼不能为空",
          trigger: "blur"
        },],
        unitId: [{
          required: true,
          message: "单元不能为空",
          trigger: "blur"
        },],
        floorId: [{
          required: true,
          message: "楼层不能为空",
          trigger: "blur"
        },],
        roomNo: [{
          required: true,
          message: "房间号不能为空",
          trigger: "blur"
        },],
        bedNum: [{
          required: true,
          message: "床位数不能为空",
          trigger: "blur"
        },],
        occupancy: [{
          required: true,
          message: "入住人数不能为空",
          trigger: "blur"
        },],
      },
      // 宿舍楼列表
      buildingList: [],
      // 单元
      unitList: [],
      // 楼层
      floorList: [],
      showBed: false,
      // 床位列表
      bedList: [],
      isSomeAdd: true,
      selectedDormitory: [],
      // 是否禁用楼层选择框
      isSelectedBuilding: true,

      importV: false,
      fileList: [],
      tableData: [],
      importcurrentPage: 1,
      importpagesize: 10,
      importtotal: 0,
    };
  },
  created() {
    this.getBuildings()
  },
  methods: {
    async doImport() {
      let temp = [...this.tableData];
      let sdata = [];
      temp.map(x => {
        let pushTemp = {
          parkName: x['园区'],
          buildingName: x['楼栋'],
          floor: x['宿舍号'].toString().slice(0, -2),
          roomNo: x['宿舍号'],
          gender: x['宿舍性别'],
          bedNum: x['床位数'],
          chargeStandard: x['10个月收费标准']
        };
        sdata.push(pushTemp);
      });
      let loading = fullLoading(this);
      let res = await importDorm(sdata);
      loading.close();
      if (res.code == 200) {
        this.$message.success(res.msg);

        this.getList();
      }
    },
    async importVClick() {
      this.tableData = [];
      this.importV = true;
    },

    downloadMode() {
      // 第一个sheet工作簿，如果需要创建多个，对应let多个sheetXdata即可
      let sheet1data = [
        {
          '园区': "",
          '楼栋': "",
          '宿舍号': "",
          '宿舍性别': "",
          '床位数': "",
          '10个月收费标准': "",
        },
      ];

      // let sheet2data = []; // 第二个sheet工作簿
      // 转换sheet格式
      var sheet1 = XLSX.utils.json_to_sheet(sheet1data);
      // 创建一个新的空的workbook      
      var wb = XLSX.utils.book_new();
      // 为每一个工作簿设置名称并添加到workbook（excel表）中
      XLSX.utils.book_append_sheet(wb, sheet1, "宿舍导入模板");
      const workbookBlob = workbook2blob(wb);  // 辅助函数workbook2blob
      // 下载文档并添加文件名称
      openDownloadDialog(workbookBlob, "宿舍导入模板.xlsx");  // 辅助函数openDownloadDialog
    },




    handleSizeChange(val) {
      this.importpagesize = val;
    },
    handleCurrentChange(val) {
      this.importcurrentPage = val;
    },
    async fileChoose(file, fileList) {
      let data = await this.handleData(file);
      this.tableData = data;
      this.importtotal = data.length;
    },
    handleData(file) {
      let reader = new FileReader();
      reader.readAsArrayBuffer(file.raw);
      return new Promise((resolve, reject) => {
        reader.onload = (e) => {
          let data = e.target.result;
          let workbook = XLSX.read(data, { //手动转化
            type: 'binary'
          });
          //获取json格式的Excel数据
          let jsonData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook
            .SheetNames[0]], {
            defval: 'null' //单元格为空时的默认值
          });
          resolve(jsonData);
        };
      })
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    handleClose(done) {
      this.$confirm('确认关闭？').then(_ => {
        this.excelData = [];
        this.fileList = [];
        done();
      }).catch(_ => { });
    },


    async listAllFloor() {
      let res = await listAllFloor();
      if (res.code == 200) {
        this.floorList = [...res.data];
      };
    },
    async syncOccupancy() {
      let loading = fullLoading(this);
      let res = await syncOccupancy();
      loading.close();
      if (res.code == 200) {
        this.$message.success(res.msg);
        this.getList();
      }
    },

    async setMoney(id) {
      let sdata = {
        id: id,
        chargeStandard: 0.00
      }
      this.$prompt('请输入金额', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async ({ value }) => {
        sdata.chargeStandard = value;
        let res = await updateDorm(sdata);
        if (res.code == 200) {
          this.$message.success(res.msg)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    /** 查询宿舍信息列表 */
    getList() {
      this.loading = true;
      listDormitory(this.queryParams).then((response) => {
        this.dormitoryList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.dormitoryList.forEach(e => {
          e.image = []
          e.photoList.forEach(i => {
            e.image.push(i.url)
          })
          e.images = e.image.join(',')
        })
      });
    },
    // 查询宿舍楼列表
    getBuildings() {
      listCampus({
        pageSize: 100000
      }).then(response => {
        var buildingList = response.rows
        listBuilding({
          pageSize: 100000
        }).then(res => {
          buildingList.forEach(e => {
            e.parkList.forEach(i => {
              i.parkList = []
              res.rows.forEach(o => {
                if (i.id == o.parkId) i.parkList.push(o)
              })
            })
          })
          this.getList()
          this.buildingList = buildingList
        })
      })
    },
    // 查询楼层
    getFloorList(queryParams) {
      listFloor(queryParams).then(res => {
        this.floorList = res.rows;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        unitId: null,
        floorId: null,
        roomNo: null,
        bedNum: null,
        occupancy: null,
        remark: null,
        photoList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectedDormitory = selection.map(item => item.roomNo)
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.listAllFloor();
      this.reset();
      this.open = true;
      this.title = "添加宿舍信息";
      this.isSomeAdd = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.listAllFloor();
      this.isSomeAdd = true
      this.reset();
      const id = row.id || this.ids;
      getDormitory(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改宿舍信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      //console.log(this.form.photoList);
      if (isEmpty(this.form.photoList)) {
        this.form.photoList = "";
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateDormitory(this.form).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            if (this.isSomeAdd) {
              addDormitory(this.form).then((response) => {
                if (response.code == 200) {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
              return
            }
            addSomeDormitory(this.form).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("批量新增成功");
                this.open = false;
                this.getList();
                this.isSomeAdd = true
              }
            })
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let ids = [row.id]
      let selectedDormitory = row.roomNo
      if (!row.id) {
        ids = this.ids
        selectedDormitory = this.selectedDormitory
      }
      this.$modal
        .confirm('是否确认删除宿舍号为"' + selectedDormitory + '"的数据项？')
        .then(function () {
          return delDormitory(ids);
        })
        .then((res) => {
          if (res.code == 200) {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          }
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "/dormitory/dms-dormitory/export", {
        ...this.queryParams,
      },
        `宿舍信息_${new Date().getTime()}.xlsx`
      );
    },
    changeBuilding(value) {
      if (!value.length) {
        this.floorList = []
        this.queryParams.floorId = null
        this.queryParams.buildingId = null
        return
      }
      this.queryParams = {
        ...this.queryParams,
        floorId: null,
        buildingId: value[2]
      }
      this.getFloorList({
        buildingId: this.queryParams.buildingId
      })
    },
    changeFormBuilding(value) {
      if (!value || !value.length) return
      this.form = {
        ...this.form,
        floorId: null,
        buildingId: value[2]
      }
      this.isSelectedBuilding = false
      this.getFloorList({
        buildingId: this.form.buildingId
      })

    },
    // 查看宿舍床位
    toDormitory(dormitoryId) {
      this.bedList = null;
      listStudent(dormitoryId).then(res => {
        if (res.code == 200) {
          if (!isEmpty(res.data)) {
            this.bedList = [...res.data];
          }
          this.showBed = true;
        }

      })
    },
    // 批量添加宿舍
    handleSomeAdd() {
      this.title = "批量添加宿舍"
      this.reset();
      this.open = true;
      this.isSomeAdd = false

    },

  },
  filters: {
    filterIsLive(value) {
      if (value == 0) return "否"
      return "是"
    },
    filterStuCode(value) {
      if (!value) return "暂无"
      return value
    },
    filterName(value) {
      if (!value) return "暂无"
      return value
    }
  },
  watch: {
    open(newValue) {
      if (newValue) {
        this.isSelectedBuilding = true
      } else {
        this.isSelectedBuilding = false
        this.floorList = []
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.building {
  width: 100%;
  height: 60px;
  margin-bottom: 20px;
  border-radius: 10px;
  padding: 10px 10px 10px 0;

  .building-item {
    width: 100px;
    height: 50px;
    background-color: #999;
    border-radius: 50px;
  }
}

.unit,
.floor {
  display: flex;
  flex-direction: column;
  width: 100px;
  transition: 1s linear;
}

.time {
  font-size: 13px;
  color: #999;

}

.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  height: 150px;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}


.active {
  box-shadow: 0px 0px 8px 2px rgba(0, 120, 255, 0.5);
}
</style>
